package com.kqb.sgpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kqb.sgpicturebackend.annotation.AuthCheck;
import com.kqb.sgpicturebackend.common.BaseResponse;
import com.kqb.sgpicturebackend.common.DeleteRequest;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.common.ResultUtils;
import com.kqb.sgpicturebackend.constant.UserConstant;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.model.dto.picture.*;
import com.kqb.sgpicturebackend.model.pojo.Picture;
import com.kqb.sgpicturebackend.model.pojo.PictureTagCategory;
import com.kqb.sgpicturebackend.model.pojo.User;
import com.kqb.sgpicturebackend.model.vo.PictureVO;
import com.kqb.sgpicturebackend.model.vo.UserVO;
import com.kqb.sgpicturebackend.service.PictureService;
import com.kqb.sgpicturebackend.service.UserService;
import com.kqb.sgpicturebackend.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/4/28 23:30
 * @description:
 */

@RestController
@Api(tags = "图片")
@RequestMapping("/picture")
public class PictureController {
    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @PostMapping("/upload")
    @ApiOperation(value = "上传图片")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/upload/url")
    @ApiOperation(value = "上传图片(url)")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            PictureUploadByUrlRequest pictureUploadByUrlRequest,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        ThrowUtils.throwNotIf(pictureUploadByUrlRequest.getFileUrl() == null, new BusinessException(ErrorCode.PARAMS_ERROR, "图片url不能为空"));
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(pictureUploadByUrlRequest.getFileUrl(), pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwNotIf(pictureUploadByBatchRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空"));
        isLogin(request);
        User loginUser = userService.getLoginUser(request);
        int fileCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(fileCount);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除图片")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deletePictureById(
            DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest.getId() != null, new BusinessException(ErrorCode.PARAMS_ERROR, "图片id不能为空"));
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(pictureService.deletePictureById(deleteRequest.getId(), loginUser));
    }


    @PostMapping("/list/page")
    @ApiOperation(value = "分页查看图片列表(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        isLogin(request);
        Page<Picture> picturePage = pictureService.queryPictureListPage(pictureQueryRequest);
        return ResultUtils.success(picturePage);
    }

    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页查看图片列表(用户)")
    public BaseResponse<Page<PictureVO>> listPictureVoByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        return ResultUtils.success(pictureService.queryPictureVoListPage(pictureQueryRequest));
    }

    /**
     * 根据id获取图片
     */
    @GetMapping("/get")
    @ApiOperation(value = "根据id获取图片")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, new BusinessException(ErrorCode.PARAMS_ERROR));
        isLogin(request);
        Picture picture = pictureService.getById(id);
        return ResultUtils.success(picture);
    }

    /**
     * 根据id获取图片vo
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据id获取图片vo")
    public BaseResponse<PictureVO> getPictureVoById(long id, HttpServletRequest request) {
        ThrowUtils.throwNotIf(id <= 0, new BusinessException(ErrorCode.PARAMS_ERROR));
        isLogin(request);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwNotIf(ObjectUtil.isNull(picture), new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        if (userId != null) {
            User user = userService.getById(userId);
            pictureVO.setUserVO(BeanUtil.copyProperties(user, UserVO.class));
        }
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/edit")
    @ApiOperation(value = "编辑图片")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        ThrowUtils.throwNotIf(pictureEditRequest == null || pictureEditRequest.getId() == null || pictureEditRequest.getId() <= 0, new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空"));
        isLogin(request);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }


    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> reviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwNotIf(pictureReviewRequest == null || pictureReviewRequest.getId() == null || pictureReviewRequest.getId() <= 0, new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误"));
        isLogin(request);
        User loginUser = userService.getLoginUser(request);
        pictureService.reviewPicture(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 判断用户是否登录
     *
     * @param request
     */
    private void isLogin(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtil.isNotEmpty(loginUser), new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "请先登录"));
    }

}
